<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="无人机" :label-width="labelWidth" prop="uavId">
        <el-select v-model="form.uavId" :clearable="true" :fit-input-width="true">
          <el-option
            v-for="(item, index) in uavInfoList"
            :key="item ? item.id : index"
            :label="item ? item.name : ''"
            :value="item ? item.id : 0" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="飞行里程" :label-width="labelWidth" prop="flightDistance">
        <div class="mo-input--number">
          <ElInputNumber v-model="form.flightDistance" controls-position="right" clearable />
          <div class="define-append">公里</div>
        </div>
      </ElFormItem>
      <ElFormItem label="飞行时长" :label-width="labelWidth" prop="flightTime">
        <div class="mo-input--number">
          <ElInputNumber v-model="form.flightTime" controls-position="right" clearable />
          <div class="define-append">小时</div>
        </div>
      </ElFormItem>
      <ElFormItem label="任务类型" :label-width="labelWidth" prop="taskCode">
        <el-select v-model="form.taskCode" :clearable="true" :fit-input-width="true">
          <el-option v-for="item in UavRecord.TaskCodeEnum" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="使用时间" :label-width="labelWidth" prop="useDate">
        <el-date-picker
          v-model="form.useDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="userDateDisabledDate" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { FormType } from '@/enums'
import { UavRecord, getUavRecordDetail, saveOrUpdateUavRecord } from '@api/tby/mountains/uavRecord'
import { UavInfo, listUavInfo } from '@api/tby/mountains/uavInfo'
import { validateDecimalTwoInteger, dateFormat } from '@/api/modules/tby/common/common'

const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<UavRecord.Form>>({})
const uavInfoList = ref<Partial<UavInfo.Record[]>>()

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

/**限制使用时间不能晚于当前时间 */
const userDateDisabledDate = (time: any) => {
  return new Date(dateFormat(time.getTime(), 'yyyy-MM-dd HH:mm:ss')).getTime() > new Date().getTime()
}

const rules = reactive<FormRules>({
  navId: [{ required: true, message: '请选择无人机', trigger: 'blur' }],
  flightDistance: [
    { required: true, message: '请输入飞行里程', trigger: 'blur' },
    { validator: validateDecimalTwoInteger, trigger: 'blur' }
  ],
  flightTime: [
    { required: true, message: '请输入飞行时长', trigger: 'blur' },
    { validator: validateDecimalTwoInteger, trigger: 'blur' }
  ],
  taskCode: [{ required: true, message: '请选择任务类型', trigger: 'blur' }],
  useDate: [{ required: true, message: '请选择使用时间', trigger: 'blur' }]
})

const open = async (type: FormType, id?: number) => {
  let uavInfoQuery: UavInfo.Query = { current: 1, size: 1000 }
  const { data } = await listUavInfo(uavInfoQuery)
  uavInfoList.value = data
  form.value = {}
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getUavRecordDetail(id!)
      loading.value = false
      form.value = data
      form.value.useDate = form.value.useDateFormat
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) {
    return
  }
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateUavRecord(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>

<style scoped lang="scss">
.mo-input--number {
  border: 1px solid #dcdfe6;
  display: flex;
  border-radius: 4px;
  .el-input-number--mini {
    flex: 1;
  }
  ::v-deep .el-input__inner {
    border: none !important;
  }
}
.define-append {
  width: 40px;
  display: inline-block;
  background: #f5f7fa;
  padding: 0px 3px;
  border-left: none;
  height: 32px;
  line-height: 32px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>
